package net.wicp.tams.common.connector.beans.property;

import net.wicp.tams.common.Result;
import net.wicp.tams.common.connector.constant.ColProperty;
import net.wicp.tams.common.exception.ExceptAll;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("rawtypes")
public class EnumHandler extends BasicHandler {
	private static final long serialVersionUID = 1L;
	private final static Logger logger = LoggerFactory.getLogger(EnumHandler.class);

	private Class beanClass;//

	public EnumHandler(String name, Class type, Class contentType) {
		super(name, type, contentType);
		this.beanClass = contentType;
	}

	public EnumHandler(String name, Class type) {
		super(name, type);
		this.beanClass = type;
	}

	@Override
	protected Result checkSingleValue(Object value) {
		String errorMsg = null;
		if (!isNull() && value == null) {
			errorMsg = "[" + name + "]不允许传空值";
		} else if (value != null && !value.getClass().isAssignableFrom(this.beanClass)) {
			errorMsg = String.format("[%s]的类型不匹配，应该是[%s],但传进来的参数是[%s]基本类型", name, beanClass.getName(),
					value.getClass().getName());
		}
		if (StringUtils.isBlank(errorMsg)) {
			return Result.getSuc();
		} else {
			logger.error(errorMsg);
			return Result.getError(errorMsg);
		}
	}

	@Override
	protected Object singleObjToJson(Object singleValue) {
		Enum tempobj = (Enum) singleValue;
		return tempobj == null ? null : tempobj.name();
	}

	@Override
	@SuppressWarnings("unchecked")
	protected Object jsonTosingleObj(Object obj) {
		return Enum.valueOf(beanClass, (String) obj);
	}

	@Override
	@SuppressWarnings("unchecked")
	public Object getSingleDefaultColValue() {
		String defaultValue = getAttriValue(ColProperty.defaultValue);
		if (StringUtils.isBlank(defaultValue)) {
			return null;
		} else {
			return Enum.valueOf(beanClass, (String) defaultValue);
		}
	}

	@Override
	protected Object mockObj() {
		String defaultValue = getAttriValue(ColProperty.defaultValue);
		if (StringUtils.isBlank(defaultValue)) {
			Object[] enumConstants = beanClass.getEnumConstants();
			if (ArrayUtils.isNotEmpty(enumConstants)) {
				return enumConstants[0];
			} else {
				return null;
			}
		} else {
			return Enum.valueOf(beanClass, (String) defaultValue);
		}
	}

}
